import { defineStore } from "pinia";
import type { User, LoginForm, RegisterForm, UserState } from "@/types";
import { AuthAPI } from "@/api/auth";
import { LocalStorage } from "@/utils/storage";

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    user: null,
    isLoggedIn: false,
    token: null,
    bookshelf: [],
    readingHistory: [],
    readerSettings: {
      fontSize: 16,
      lineHeight: 1.6,
      backgroundColor: "#ffffff",
      textColor: "#333333",
      fontFamily: "system-ui",
      pageWidth: 800,
      nightMode: false,
    },
    walletPassword: null,
    paymentRecords: [],
    _initialized: false, // 添加初始化标志
    _authListenerAdded: false, // 添加监听器标志
  }),

  getters: {
    isAdmin: (state) => {
      if (!state.user) return false;
      // 检查用户名、邮箱或ID来判断管理员权限
      return (
        state.user.username === "admin" ||
        state.user.username === "admin_gkl" ||
        state.user.email === "1477042095@qq.com" ||
        state.user.nickname === "超级管理员" ||
        state.user.id === 1 ||
        state.user.id === "1" ||
        state.user.id === 3 ||
        state.user.id === "3"
      );
    },
    isModerator: (state) => {
      if (!state.user) return false;
      return (
        state.user.username === "admin" ||
        state.user.username === "admin_gkl" ||
        state.user.email === "1477042095@qq.com" ||
        state.user.nickname === "超级管理员" ||
        state.user.id === 1 ||
        state.user.id === "1" ||
        state.user.id === 3 ||
        state.user.id === "3"
      );
    },
    isVip: (state) => {
      if (!state.user) return false;

      // 检查后端字段 (数据库中is_vip为1，需要检查1和true)
      if (state.user.is_vip === true || state.user.is_vip === 1) return true;

      // 检查后端VIP过期时间字段
      if (state.user.vip_expire_date) {
        return new Date(state.user.vip_expire_date) > new Date();
      }

      // 检查前端字段和过期时间
      if (state.user.vipStatus && state.user.vipStatus !== "none") {
        if (state.user.vipExpireDate) {
          return new Date(state.user.vipExpireDate) > new Date();
        }
        return true;
      }

      // 检查其他可能的VIP过期时间字段
      if (state.user.vip_expires_at) {
        return new Date(state.user.vip_expires_at) > new Date();
      }

      return false;
    },

    // 获取用户余额（兼容前端和后端字段）
    userBalance: (state) => {
      if (!state.user) return 0;
      return state.user.balance || state.user.coins || 0;
    },

    isActive: (state) => true,
    canManageUsers: (state) => {
      if (!state.user) return false;
      return (
        state.user.username === "admin" ||
        state.user.username === "admin_gkl" ||
        state.user.email === "1477042095@qq.com" ||
        state.user.nickname === "超级管理员" ||
        state.user.id === 1 ||
        state.user.id === "1" ||
        state.user.id === 3 ||
        state.user.id === "3"
      );
    },
    isInitialized: (state) => state._initialized,
  },

  actions: {
    // 初始化用户状态
    async initUser() {
      // 如果已经初始化过，直接返回
      if (this._initialized) {
        console.log("用户已初始化，跳过重复初始化");
        return;
      }

      console.log("开始初始化用户状态...");

      // 只添加一次认证失效事件监听器
      if (!this._authListenerAdded) {
        window.addEventListener("auth:unauthorized", this.handleAuthUnauthorized);
        this._authListenerAdded = true;
        console.log("已添加认证失效事件监听器");
      }

      try {
        // 检查是否有token（优先从localStorage，然后从sessionStorage）
        const storedToken = LocalStorage.getTokenFromStorage();
        console.log("获取到的token:", storedToken ? "存在" : "不存在");

        if (!storedToken) {
          // 没有token，直接设置为未登录状态
          this.user = null;
          this.token = null;
          this.isLoggedIn = false;
          this._initialized = true;
          console.log("无token，设置为未登录状态");
          return;
        }

        console.log("有token，开始验证...");
        // 有token，验证其有效性
        const result = await AuthAPI.checkAuthStatus();
        console.log("验证结果:", result);

        if (result.success && "user" in result && result.user) {
          this.user = result.user;
          this.token = storedToken;
          this.isLoggedIn = true;
          console.log("用户验证成功:", result.user.nickname || result.user.email);
        } else {
          // token无效，清理状态
          this.user = null;
          this.token = null;
          this.isLoggedIn = false;
          LocalStorage.clearAllTokens();
          console.log("token无效，已清理状态");
        }
      } catch (error) {
        console.error("初始化用户状态失败:", error);
        this.user = null;
        this.token = null;
        this.isLoggedIn = false;
        // 清理可能无效的token
        LocalStorage.clearAllTokens();
      } finally {
        this._initialized = true;
        console.log("用户初始化完成，状态:", {
          isLoggedIn: this.isLoggedIn,
          user: this.user ? { id: this.user.id, nickname: this.user.nickname } : null,
        });
      }
    },

    // 处理认证失效
    handleAuthUnauthorized() {
      // 清理用户状态
      this.user = null;
      this.token = null;
      this.isLoggedIn = false;
      this.bookshelf = [];

      // 清除所有token和记住登录相关数据
      LocalStorage.clearAllTokens();

      // 如果不是记住登录，也清除记住的邮箱
      if (!LocalStorage.getRememberLogin()) {
        LocalStorage.clearRememberedEmail();
      }

      // 重置初始化状态
      this._initialized = false;
      this._authListenerAdded = false;

      // 清理事件监听器
      window.removeEventListener("auth:unauthorized", this.handleAuthUnauthorized);

      // 使用Vue Router进行导航，避免硬跳转
      if (window.location.pathname !== "/auth/login") {
        // 使用事件总线，让App.vue来处理导航
        window.dispatchEvent(
          new CustomEvent("auth:redirect", {
            detail: { path: "/auth/login" },
          }),
        );
      }
    },

    // 用户登录
    async login(loginForm: LoginForm) {
      try {
        const result = await AuthAPI.login(loginForm);

        if (result.success) {
          this.user = result.user || null;
          this.token = result.token || null;
          this.isLoggedIn = true;

          // 根据remember状态保存token
          if (result.token) {
            LocalStorage.setTokenWithRemember(result.token, loginForm.remember);
          }

          // 如果选择记住登录，保存邮箱
          if (loginForm.remember) {
            LocalStorage.setRememberedEmail(loginForm.email);
          } else {
            LocalStorage.clearRememberedEmail();
          }

          return { success: true, message: result.message };
        } else {
          return { success: false, message: result.message };
        }
      } catch (error) {
        const message = (error as Error).message || "登录失败";
        return { success: false, message };
      }
    },

    // 用户注册
    async register(registerForm: RegisterForm) {
      try {
        const result = await AuthAPI.register(registerForm);

        if (result.success) {
          this.user = result.user || null;
          this.token = result.token || null;
          this.isLoggedIn = true;

          // 注册后默认记住登录
          if (result.token) {
            LocalStorage.setTokenWithRemember(result.token, true);
          }

          return { success: true, message: result.message };
        } else {
          return { success: false, message: result.message };
        }
      } catch (error) {
        const message = (error as Error).message || "注册失败";
        return { success: false, message };
      }
    },

    // 用户退出
    async logout() {
      try {
        await AuthAPI.logout();
      } catch (error) {
        console.error("退出登录失败:", error);
      } finally {
        this.user = null;
        this.token = null;
        this.isLoggedIn = false;
        this.bookshelf = [];

        // 清除所有token
        LocalStorage.clearAllTokens();

        // 根据remember状态决定是否清除记住的邮箱
        if (!LocalStorage.getRememberLogin()) {
          LocalStorage.clearRememberedEmail();
        }

        // 清除记住登录状态
        LocalStorage.clearRememberLogin();

        // 重置初始化状态，允许重新初始化
        this._initialized = false;
        this._authListenerAdded = false;

        // 清理事件监听器
        window.removeEventListener("auth:unauthorized", this.handleAuthUnauthorized);
      }
    },

    // 更新阅读器设置
    updateReaderSettings(settings: Partial<typeof this.readerSettings>) {
      this.readerSettings = { ...this.readerSettings, ...settings };
      localStorage.setItem("novel_app_reader_settings", JSON.stringify(this.readerSettings));
    },

    // 初始化阅读器设置
    initReaderSettings() {
      try {
        const stored = localStorage.getItem("novel_app_reader_settings");
        if (stored) {
          this.readerSettings = { ...this.readerSettings, ...JSON.parse(stored) };
        }
      } catch (error) {
        console.error("初始化阅读器设置失败:", error);
      }
    },

    // 加载阅读器设置
    loadReaderSettings() {
      try {
        const stored = localStorage.getItem("novel_app_reader_settings");
        if (stored) {
          this.readerSettings = { ...this.readerSettings, ...JSON.parse(stored) };
        }
      } catch (error) {
        console.error("加载阅读器设置失败:", error);
      }
    },

    // 获取用户书架
    async fetchBookshelf() {
      if (!this.user?.id) return;

      try {
        // 这里可以添加实际的API调用
        // const bookshelfData = await BookshelfAPI.getUserBookshelf(this.user.id);
        // this.bookshelf = bookshelfData;
        console.log("获取书架数据...");
      } catch (error) {
        console.error("获取书架失败:", error);
      }
    },

    // 更新用户信息
    async updateUserInfo(userInfo: Partial<User>) {
      if (!this.user) return false;

      try {
        // 这里可以添加实际的API调用
        // const result = await UserAPI.updateUserInfo(this.user.id, userInfo);
        // if (result.success) {
        //   this.user = { ...this.user, ...userInfo };
        // }
        this.user = { ...this.user, ...userInfo };
        console.log("更新用户信息:", userInfo);
        return true;
      } catch (error) {
        console.error("更新用户信息失败:", error);
        return false;
      }
    },

    // 获取充值套餐
    getRechargePackages() {
      // 返回模拟的充值套餐数据
      return [
        { id: 1, amount: 10, bonus: 0, price: 10, label: "10元", description: "基础充值" },
        { id: 2, amount: 50, bonus: 5, price: 50, label: "50元", description: "赠送5元" },
        { id: 3, amount: 100, bonus: 15, price: 100, label: "100元", description: "赠送15元" },
        { id: 4, amount: 200, bonus: 40, price: 200, label: "200元", description: "赠送40元" },
        { id: 5, amount: 500, bonus: 120, price: 500, label: "500元", description: "赠送120元" },
      ];
    },

    // 处理充值
    async processRecharge(
      packageInfo: { amount: number; bonus: number; price: number },
      paymentPassword: string,
    ) {
      try {
        // 这里可以添加实际的API调用
        // const result = await PaymentAPI.processRecharge(packageInfo, paymentPassword);
        console.log("处理充值:", packageInfo, "密码:", paymentPassword);

        // 模拟充值成功
        if (this.user) {
          const totalAmount = packageInfo.amount + (packageInfo.bonus || 0);
          this.user.balance = (this.user.balance || 0) + totalAmount;
          this.user.totalRecharge = (this.user.totalRecharge || 0) + packageInfo.price;
        }

        return { success: true, message: "充值成功" };
      } catch (error) {
        console.error("充值处理失败:", error);
        return { success: false, message: "充值失败" };
      }
    },

    // 获取支付记录
    async fetchPaymentRecords() {
      try {
        // 这里可以添加实际的API调用
        // const records = await PaymentAPI.getPaymentRecords(this.user?.id);
        // this.paymentRecords = records;
        console.log("获取支付记录...");

        // 模拟支付记录数据
        this.paymentRecords = [
          {
            id: "1",
            userId: this.user?.id?.toString() || "",
            type: "recharge",
            amount: 100,
            status: "success",
            description: "充值",
            createdAt: new Date().toISOString(),
          },
        ];
      } catch (error) {
        console.error("获取支付记录失败:", error);
      }
    },

    // 检查章节是否可访问（VIP用户免费，普通用户需购买）
    canAccessChapter(chapter: { id: string; isVip: boolean; isFree: boolean; price?: number }) {
      if (!chapter.isVip) return true; // 非VIP章节，所有人可访问
      if (chapter.isFree) return true; // 免费章节
      if (this.isVip) return true; // VIP用户可免费访问所有VIP章节

      // 普通用户检查是否已购买
      return this.user?.purchasedChapters?.includes(chapter.id) || false;
    },

    // 获取章节访问状态
    getChapterAccessInfo(chapter: { id: string; isVip: boolean; isFree: boolean; price?: number }) {
      if (!chapter.isVip) {
        return { canAccess: true, needPurchase: false, price: 0, reason: "" };
      }

      if (chapter.isFree) {
        return { canAccess: true, needPurchase: false, price: 0, reason: "免费章节" };
      }

      if (this.isVip) {
        return { canAccess: true, needPurchase: false, price: 0, reason: "VIP免费" };
      }

      const hasPurchased = this.user?.purchasedChapters?.includes(chapter.id);
      if (hasPurchased) {
        return { canAccess: true, needPurchase: false, price: 0, reason: "已购买" };
      }

      return {
        canAccess: false,
        needPurchase: true,
        price: chapter.price || 1,
        reason: "需要购买",
      };
    },

    // 记录阅读历史
    async recordReading(novelId: string, chapterId: string, duration: number = 0) {
      if (!this.user?.id) return false;

      try {
        // 这里可以添加实际的API调用
        // const result = await RecordAPI.recordReading(this.user.id, novelId, chapterId, duration);
        console.log("记录阅读历史:", { novelId, chapterId, duration });
        // 实际项目中应该使用完整的阅读历史数据结构
        console.log("阅读历史记录:", { novelId, chapterId, duration });
        if (this.readingHistory.length > 100) {
          this.readingHistory = this.readingHistory.slice(0, 100);
        }

        return true;
      } catch (error) {
        console.error("记录阅读历史失败:", error);
        return false;
      }
    },

    // 购买章节
    async buyChapter(chapterId: string, price: number) {
      if (!this.user?.id) return false;

      try {
        // 检查余额
        if (this.userBalance < price) {
          return false;
        }

        // 这里可以添加实际的API调用
        // const result = await PaymentAPI.buyChapter(this.user.id, chapterId, price);
        console.log("购买章节:", { chapterId, price });

        // 更新用户余额和已购买章节
        if (this.user.balance !== undefined) {
          this.user.balance = this.user.balance - price;
        } else if (this.user.coins !== undefined) {
          this.user.coins = this.user.coins - price;
        }

        if (!this.user.purchasedChapters) {
          this.user.purchasedChapters = [];
        }
        this.user.purchasedChapters.push(chapterId);

        // 更新总消费
        this.user.totalConsumption = (this.user.totalConsumption || 0) + price;

        return true;
      } catch (error) {
        console.error("购买章节失败:", error);
        return false;
      }
    },

    // 添加到书架
    async addToBookshelf(novelId: string) {
      if (!this.user?.id) return false;

      try {
        // 这里可以添加实际的API调用
        // const result = await BookshelfAPI.addToBookshelf(this.user.id, novelId);
        console.log("添加到书架:", novelId);

        // 更新本地书架 - 这里需要实际的API调用来获取完整的书架项目
        if (!this.bookshelf.find((item) => item.novelId === novelId)) {
          // 实际项目中应该调用API来添加到书架，这里只是模拟
          console.log("应该调用API添加到书架:", novelId);
        }

        return true;
      } catch (error) {
        console.error("添加到书架失败:", error);
        return false;
      }
    },

    // 从书架移除
    async removeFromBookshelf(item: { id?: string; novelId?: string; novel?: { id: string } }) {
      if (!this.user?.id) return false;

      try {
        // 这里可以添加实际的API调用
        // const result = await BookshelfAPI.removeFromBookshelf(this.user.id, item.novelId || item.id);
        console.log("从书架移除:", item);

        // 更新本地书架
        const novelId = item.novelId || item.novel?.id || item.id;
        this.bookshelf = this.bookshelf.filter(
          (bookshelfItem) => bookshelfItem.novelId !== novelId && bookshelfItem.id !== novelId,
        );

        return true;
      } catch (error) {
        console.error("从书架移除失败:", error);
        return false;
      }
    },
  },
});
